<template>
  <el-form :model="dataForm" :rules="rules" label-position="top" class="form-box" ref="dataFormRef"
    @keyup.enter="dataFormSubmitHandle()" label-width="120px">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item prop="name" label="学校名称">
          <el-input v-model="dataForm.name" placeholder="请输入"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item class="footer-btn">
      <el-button @click="cancelHandle()">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();
const row: any = JSON.parse(route.query?.row as string || '{}');
const dataFormRef = ref();

const dataForm = reactive({
  id: "",
  name: "",
  type: "SCHOOL",
});

const rules = ref({
  name: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
});

const init = () => {
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (row?.id) {
    Object.assign(dataForm, row);
  }
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    baseService.post(`/study/dept/${!dataForm.id ? 'save' : 'update'}`, dataForm).then((res) => {
      ElMessage.success({
        message: "成功",
        duration: 500,
        onClose: () => {
          router.push('/study/school');
        }
      });
    });
  });
};

const cancelHandle = () => {
  router.go(-1);
};

onMounted(() => {
  init();
})
</script>
